package MusicLandscape.util.formatters;

import MusicLandscape.entities.Track;
import MusicLandscape.util.MyFormatter;

/**
 * This class represents the concept of csv-formatting of a track.
 *
 * @author Jonas Altrock (ew20b126@technikum-wien.at)
 * @version 6
 * @since ExerciseSheet04
 */
public class CSVTrackFormatter implements MyFormatter<Track> {
    /**
     * comma separated list of all column names in the following order:
     *
     * <ol>
     *   <li>Title</li>
     *   <li>Writer</li>
     *   <li>Performer</li>
     *   <li>Duration</li>
     *   <li>Year</li>
     * </ol>
     * <p>
     * No new line is added at the end of the String!.
     */
    @Override
    public String header() {
        return "Title," +
                "Writer," +
                "Performer," +
                "Duration," +
                "Year";
    }

    /**
     * Creates a CSV format of a track.
     * <p>
     * No new line is added at the end of the String!
     *
     * @param t the track to be formatted
     * @return the formatted String representing the track
     */
    @Override
    public String format(Track t) {
        return field(t.getTitle()) +
                ", " +
                field(t.getWriter()) +
                ", " +
                field(t.getPerformer()) +
                ", " +
                field(t.getDuration()) +
                ", " +
                field(t.getYear());
    }

    /**
     * the top separator for this format is the empty string.<br>
     * No new line is added at the end of the String!.
     *
     * @return the separator.
     */
    @Override
    public String topSeparator() {
        return "";
    }


    /**
     * Prepare a field value for CSV output.
     *
     * @param o the object to stringify
     * @return a possibly quoted field value for CSV
     */
    private String field(Object o) {
        String val = o.toString();
        boolean needsQuotes = false;

        if (val.indexOf("\"") > 0) {
            needsQuotes = true;
            val = val.replace("\"", "\\\"");
        }

        if (val.indexOf(",") > 0) {
            needsQuotes = true;
        }

        if (needsQuotes) {
            val = '"' + val + '"';
        }

        return val;
    }

    /**
     * the string representation is "CSV format [Title, Writer, Performer, duration, year]" (without quotes)
     *
     * @return a string representation of the object.
     */
    @Override
    public String toString() {
        return "CSV format [Title, Writer, Performer, duration, year]";
    }
}
